import * as Cesium from 'cesium'

class LabelPrimitiveManage {

  constructor(options) {
    this.labelCollection = new Cesium.LabelCollection({
      blendOption:Cesium.BlendOption.OPAQUE,
      ...options
    })
    this._collection = new Cesium.AssociativeArray()
  }

  add(labelParams){
    const {id} = labelParams;

    const renderId = Cesium.defined(id)?id:Cesium.createGuid();

    const label = this.labelCollection.add({...labelParams})
    label.id = label;
    label.renderId = renderId;

    this._collection.set(renderId,label)

    return label;
  }

  contains(label){
    return  this.labelCollection.contains(label)
  }

  destroy(){
    this._collection.removeAll()
    this.labelCollection.destroy();
  }

  get(index){
    return this.labelCollection.get(index)
  }

  getById(key){
    return this._collection.get(key)
  }

  isDestroyed(){
    return this.labelCollection.isDestroyed()
  }

  remove(label){
    const findIndex = this._collection.values.findIndex(val => val === label);

    if(findIndex === -1){
      console.warn(`LabelPrimitiveManager.js collectin not find:`,label);
    }else{
      const resultId = this._collection.values[findIndex].renderId;
      this._collection.remove(resultId)
    }

    return this.labelCollection.remove(label)
  }

  removeById(key){
    const label = this._collection.get(key)
    return this.remove(label)
  }

  removeAll(){
    this._collection.removeAll()
    this.labelCollection.removeAll()
  }

  update(frame){
    if(this.isDestroyed()){
      return false
    }

    this.labelCollection.update(frame)
  }
}

export default LabelPrimitiveManage